//
//  MobileWeatherView.m
//  IOSMobileManager
//
//  Created by Javor on 15/9/18.
//  Copyright (c) 2015年 JavorFeng. All rights reserved.
//


#import "MobileWeatherView.h"
#import "Constant.h"
#import "EnvironmentVariable.h"
#import "JFLanguageManager.h"

@implementation MobileWeatherView {
    CLLocationManager *_locationManager;
    NSString *_cityName;
    
    UILabel *_tempLabel;
    UILabel *_tempSignLabel;
    UILabel *_tempHighLowLabel;
    UILabel *_dateLabel;
    UIImageView *_weatherImageView;
    UILabel *_weatherLabel;
    UILabel *_locationLabel;
    
    UIButton *_optionButton;
    UIButton *_aboutButton;
    UIButton *_helpButton;
    
    UIImageView *_optionImageView;
    UIImageView *_aboutImageView;
    UIImageView *_helpImageView;
    
    UIView *_bottomView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor whiteColor];
        if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        }else{
            //开启定位
            _locationManager = [[CLLocationManager alloc] init];//创建位置管理器
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                [_locationManager requestWhenInUseAuthorization];
            }
            _locationManager.delegate=self;
            _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
            _locationManager.distanceFilter=1000.0f;
            //启动位置更新
            [_locationManager startUpdatingLocation];
        }
        [self createView];
    }
    return self;
}

- (void)createView {
    //温度
    _tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(18, 60, 115, 95)];
    _tempLabel.font = [UIFont fontWithName:@"AvenirNext-UltraLight" size:102];
    _tempLabel.textColor = EF_OLD_RED_COLOR;
    _tempLabel.text = @"4";
    [self addSubview:_tempLabel];
    //℃
    _tempSignLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, 60, 50, 40)];
    _tempSignLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:30];//[UIFont systemFontOfSize:40];
    _tempSignLabel.textColor = EF_OLD_RED_COLOR;
    _tempSignLabel.text = @"℃";
    [self addSubview:_tempSignLabel];
    //最高气温最低气温
    _tempHighLowLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, 120, 90, 20)];
    _tempHighLowLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:17];//[UIFont systemFontOfSize:40];
    _tempHighLowLabel.textColor = [UIColor grayColor];
    _tempHighLowLabel.text = @"4℃/8℃";
    [self addSubview:_tempHighLowLabel];
    //日期
    _dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(18, 156, 160, 20)];
    _dateLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:17];//[UIFont systemFontOfSize:40];
    _dateLabel.textColor = [UIColor blackColor];
    [self addSubview:_dateLabel];
    
    //更新日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy.MM.dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit |  NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit |  NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger week = [comps weekday];
    NSString *strWeek = [self getweek:week];
    _dateLabel.text = [[currentDateStr stringByAppendingString:@"  "] stringByAppendingString:strWeek];
    
    _weatherImageView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 60, 60, 60)];
    _weatherImageView.image = [UIImage imageNamed:@"sun_and_cloud_mini"];
    [self addSubview:_weatherImageView];

    _weatherLabel = [[UILabel alloc] initWithFrame:CGRectMake(240, 120, 40, 20)];
    _weatherLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:17];//[UIFont systemFontOfSize:40];
    _weatherLabel.textColor = [UIColor blackColor];
    _weatherLabel.text = @"晴";
    [self addSubview:_weatherLabel];
    
    _locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(240, 140, 40, 20)];
    _locationLabel.font = [UIFont fontWithName:@"AvenirNext-Regular" size:17];//[UIFont systemFontOfSize:40];
    _locationLabel.textColor = [UIColor blackColor];
    _locationLabel.text = @"达州";
    [self addSubview:_locationLabel];
    
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 160, self.frame.size.width, self.frame.size.height - 160)];
    [self addSubview:_bottomView];
    
    
    [self addBtnWithTitle:[JFLanguageManager stringWithKey:@"about" table:Table_Tools comment:@"关于"] icon:@"icon_w_about" color:[UIColor orangeColor] index:0];
    [self addBtnWithTitle:@"设置" icon:@"icon_w_option" color:[UIColor redColor] index:1];
    [self addBtnWithTitle:@"意见" icon:@"icon_w_help" color:[UIColor colorWithRed:213/255.0 green:22/255.0 blue:71/255.0 alpha:1] index:2];
}

#pragma mark --CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    [_locationManager stopUpdatingLocation];

    //得到newLocation
    CLLocation *cloc = [locations lastObject];
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:cloc completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error)
        {
            if(placemarks.count > 0){
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
                _cityName = [placemark.addressDictionary objectForKey:@"City"];
                //直辖市要通过administrativeArea取值
                if(_cityName == nil)
                    _cityName = placemark.administrativeArea;
            }
            NSString *urlString = @"http://apis.baidu.com/apistore/weatherservice/cityname?cityname=";
            urlString = [urlString stringByAppendingString:_cityName];
            NSString * encodingString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:encodingString];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            [request setValue:@"507d67d655d2bcc7dcf9fe61ff41f06c" forHTTPHeaderField:@"apikey"];
            NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
            
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&err];
            if(err) {
                NSLog(@"json解析失败：%@",err);
                return;
            }
            if([[dic objectForKey:@"errNum"] intValue] == -1)  {
                return;
            }
            [self updateWeatherInfo:[dic objectForKey:@"retData"]];
        }
    }];
}

- (void)updateWeatherInfo:(NSDictionary *)dic {
    if(dic == nil || dic.count < 1) return;
    
    //更新温度
    NSString *temp = [dic objectForKey:@"temp"];
    _tempLabel.text = temp;
    //更新最高/最低温
    NSString *lowTemp = [dic objectForKey:@"l_tmp"];
    lowTemp = [lowTemp stringByAppendingString:@"℃"];
    NSString *highTemp = [dic objectForKey:@"h_tmp"];
    highTemp = [highTemp stringByAppendingString:@"℃"];
    NSString *tempHighLow = [[highTemp stringByAppendingString:@"/"] stringByAppendingString:lowTemp];
    _tempHighLowLabel.text = tempHighLow;
    //更新地点
    NSString *location = [dic objectForKey:@"city"];
    _locationLabel.text = location;
   
    //更新天气、图标
    NSString *weather = [dic objectForKey:@"weather"];
    _weatherLabel.text = weather;
    
    if ([weather isEqualToString:@"雷阵雨"]) {
        _weatherImageView.image = [UIImage imageNamed:@"thunder_mini"];
    }else if ([weather isEqualToString:@"晴"]){
        _weatherImageView.image = [UIImage imageNamed:@"sun_mini"];
    }else if ([weather isEqualToString:@"多云"]){
        _weatherImageView.image = [UIImage imageNamed:@"sun_and_cloud_mini"];
    }else if ([weather isEqualToString:@"阴"]){
        _weatherImageView.image = [UIImage imageNamed:@"nosun_mini"];
    }else if ([weather hasSuffix:@"雨"]){
        _weatherImageView.image = [UIImage imageNamed:@"rain_mini"];
    }else if ([weather hasSuffix:@"雪"]){
        _weatherImageView.image = [UIImage imageNamed:@"snow_heavyx_mini"];
    }else{
        _weatherImageView.image = [UIImage imageNamed:@"sand_float_mini"];
    }
}

-(NSString*)getweek:(NSInteger)week
{
    NSString*weekStr=nil;
    if(week==1)
    {
        weekStr=@"星期天";
    }else if(week==2){
        weekStr=@"星期一";
        
    }else if(week==3){
        weekStr=@"星期二";
        
    }else if(week==4){
        weekStr=@"星期三";
        
    }else if(week==5){
        weekStr=@"星期四";
        
    }else if(week==6){
        weekStr=@"星期五";
        
    }else if(week==7){
        weekStr=@"星期六";
        
    }
    return weekStr;
}

- (void)addBtnWithTitle:(NSString *)title icon:(NSString *)icon color:(UIColor *)color index:(int)index{
    int cols = index%3;
    int rows = index/3;
    CGFloat w = self.frame.size.width/3;
    CGFloat h = (self.frame.size.height - 160)/2;
    UIView *itemView = [[UIView alloc]init];
    [_bottomView addSubview:itemView];
    itemView.frame = CGRectMake(cols * w, rows * h, w, h);
    
    UIButton *btn = [[UIButton alloc] init];
    btn.frame = CGRectMake(20, 40, w-40, w-40);

//    if (index > 2) {
//        btn.y = 10;
//    }
    
    btn.layer.cornerRadius = (w-40)/2;
    btn.layer.masksToBounds = YES;
    btn.backgroundColor = color;
    
    
    UIImageView *img = [[UIImageView alloc]init];
    img.image = [UIImage imageNamed:icon];
    img.frame = CGRectMake(0, 0, w-40, w-40);
    img.center = btn.center;
    
    [itemView addSubview:btn];
    [itemView addSubview:img];
    
    UILabel *titleLbl = [[UILabel alloc]init];
    titleLbl.font = [UIFont fontWithName:@"HYQiHei" size:16];
    titleLbl.text = title;
    titleLbl.frame = CGRectMake(0, btn.frame.origin.y + btn.frame.size.height, itemView.frame.size.width, 40);
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [itemView addSubview:titleLbl];
    
    switch (index) {
        case 0:
            _aboutButton = btn;
            _aboutImageView = img;
            _aboutButton.tag = 11;
            [_aboutButton addTarget:self action:@selector(customButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 1:
            _optionButton = btn;
            _optionImageView = img;
            _optionButton.tag = 12;
        [_optionButton addTarget:self action:@selector(customButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 2:
            _helpButton = btn;
            _helpImageView = img;
            _helpButton.tag = 13;
            [_helpButton addTarget:self action:@selector(customButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            break;
//        case 3:
//            self.btn4 = btn;
//            self.img4 = img;
//            break;
//        case 4:
//            self.btn5 = btn;
//            self.img5 = img;
//            break;
//        case 5:
//            self.btn6 = btn;
//            self.img6 = img;
//            break;
            
        default:
            break;
    }
}

- (void)customButtonClick:(id)sender {
    if(_delegate != nil && [_delegate respondsToSelector:@selector(weatherView:didClickButton:)]){
        [_delegate weatherView:self didClickButton:sender];
    }
}


- (void)addAnimate{
    _aboutButton.transform = CGAffineTransformMakeScale(0.2, 0.2);
    _optionButton.transform = CGAffineTransformMakeScale(0.2, 0.2);
    _helpButton.transform = CGAffineTransformMakeScale(0.2, 0.2);
    
    _aboutImageView.transform = CGAffineTransformMakeScale(1.4, 1.4);
    _optionImageView.transform = CGAffineTransformMakeScale(1.4, 1.4);
    _helpImageView.transform = CGAffineTransformMakeScale(1.4, 1.4);
   
    [UIView animateWithDuration:0.2 animations:^{
        _aboutButton.transform = CGAffineTransformMakeScale(1.2, 1.2);
        _optionButton.transform = CGAffineTransformMakeScale(1.2, 1.2);
        _helpButton.transform = CGAffineTransformMakeScale(1.2, 1.2);
        
        _aboutImageView.transform = CGAffineTransformMakeScale(0.7, 0.7);
        _optionImageView.transform = CGAffineTransformMakeScale(0.7, 0.7);
        _helpImageView.transform = CGAffineTransformMakeScale(0.7, 0.7);
        } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            _aboutButton.transform = CGAffineTransformIdentity;
            _optionButton.transform = CGAffineTransformIdentity;
            _helpButton.transform = CGAffineTransformIdentity;
            
            _aboutImageView.transform = CGAffineTransformIdentity;
            _optionImageView.transform = CGAffineTransformIdentity;
           _helpImageView.transform = CGAffineTransformIdentity;
        }];
    }];
}

@end
